window.GridChart = function(){
	// 表格引用
	this.grid = null;
	// 图表展示容器
	this.container = null;
	// XML模板
	this.xml = null;
	// 会话参数
	this.session = {};
	
	this.setGrid = function( grid ){
		this.grid = grid;
	};
	
	this.setContainer = function( container ){
		this.container = container;
	};
	
	this.setXml = function( xml ){
		this.xml = xml;
	};
	
	this.setSession = function( session ){
		this.session = session;
	};
	
	// 绑定选择行
	this.row = function(){
		var _this = this;
		this.grid.onRowSelect (function( row ){
			var charts = _this.xml.split(/(##)/g);
			// 将主图表隐藏
			jQuery("#" + _this.container).find("span[id*='Total']").hide();
			for( var i = 0 ; i < charts.length ; i++ ){
				var xml = charts[i];
				_this.draw(row,xml);
			}
		});
	};
	
	// 合计
	this.main = function(){
		var _this = this;
		var charts = _this.xml.split(/(##)/g);
		for( var i = 0 ; i < charts.length ; i++ ){
			var xml = charts[i];
			var total = this.getTotal(xml);
			this.draw(total,xml);
		}
	};
	
	
	// 绘制图表
	this.draw = function(row , xml ){
		var chart = jQuery(xml);
		var chartId = chart.attr("id") || i;
		var renderId = CipChart.getRenderId(chartId);
		var div = "<span id='" + renderId + "' style='" + chart.attr("css") + "'></span>";
		if( jQuery("#" + renderId).size() == 0 ){
			jQuery("#" + this.container).append(div);
		}
		var params = xml.match(/#\w+#/g) || [];
		for(var k = 0 ; k < params.length ; k++ ){
			var name = params[k].replace(/#/g,"");
			xml = xml.replace(params[k],row[name]);
		} 
		var width = jQuery("#" + renderId).width();
		var height = jQuery("#" + renderId).height();
		CipChart.draw({type:chart.attr("type"),width:width,height:height,xml:xml,chartId:chartId}); 
	};
	
	// 取得合计
	this.getTotal = function( xml ){
		var params = xml.match(/#\w+#/g) || [];
		var rows = this.grid.getAllRows();
		var total = {};
		for(var k = 0 ; k < rows.length ; k++ ){
			for(var m = 0 ; m < params.length ; m++ ){
				var name = params[m].replace(/#/g,"");
				total[name] = (total[name] || 0) + new Number(rows[k][name]);
			}
		}
		return total;
	};
};

window.CipChart = {};

CipChart.path = ctx + "/js/swf/";

//图表定义
CipChart.SWF = {"1":"Pie2D.swf","2":"Column3D.swf","3":"Bar2D.swf","4":"Line.swf"};

// 取得绘图层ID
CipChart.getRenderId = function( chartId ){
	return chartId + "Div";
};

// 绘制图表
CipChart.draw = function( option ){
	var chartId = option.chartId;
	var renderId = this.getRenderId(chartId);
	var isDraw = jQuery("#" + renderId).attr("isDraw");
	if( isDraw ){
		var chart = getChartFromId(chartId);
        chart.setDataXML(option.xml);
	}else{
		var swf = CipChart.path + option.type + ".swf";
		var chart = new FusionCharts(swf,chartId, option.width, option.height, "0", "1");
		chart.setDataXML(option.xml);
		chart.render(renderId);
		jQuery("#" + renderId).attr("isDraw",true);
	}
};